package springboot.springboot06_ssmp.controller;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import springboot.common_utils.R;
import springboot.springboot06_ssmp.entity.PersonalDiaries;
import springboot.springboot06_ssmp.entity.Role;
import springboot.springboot06_ssmp.entity.SendBack;
import springboot.springboot06_ssmp.entity.User;
import springboot.springboot06_ssmp.mapper.PersonalDiariesMapper;
import springboot.springboot06_ssmp.service.IPersonalDiariesService;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 个人日记 前端控制器
 * </p>
 *
 * @author daiqiang
 * @since 2024-02-23
 */
@Slf4j
@CrossOrigin  //允许跨域
@RestController
@RequestMapping("personalDiaries")
public class PersonalDiariesController {
    @Autowired
    private IPersonalDiariesService personalDiariesService;
    @Autowired
    private PersonalDiariesMapper personalDiariesMapper;

    @GetMapping
    public R getAll(){
        List<PersonalDiaries> resultList = personalDiariesService.list();

        // 对结果列表进行排序，假设要按照对象的某个属性排序，比如按照对象的id属性序排序
        resultList = resultList.stream()
                .sorted(Comparator.comparing(PersonalDiaries::getId).reversed())
                .collect(Collectors.toList());

        //return R.success(personalDiariesService.list());
        return R.success(resultList);
    }


    @PostMapping
    public R save(@RequestBody PersonalDiaries personalDiaries) {

        personalDiaries.setUserId("daiqiang");
       // personalDiaries.setUpdateDate(LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(new Date())));
        personalDiaries.setUpdateDate(LocalDate.parse(DateUtil.today()));
        System.out.println(personalDiaries);
        try {
            personalDiariesService.save(personalDiaries);
            return R.success("success");
        } catch (Exception e) {

            return R.fail("fail");
        }
    }
    @PutMapping
    public  R update(@RequestBody PersonalDiaries personalDiaries){
        System.out.println("----》"+personalDiaries);
        return  R.success(personalDiariesService.updateById(personalDiaries));
    }
    @DeleteMapping("{id}")
    public  R delete(@PathVariable Integer id){
        return  R.success(personalDiariesService.removeById(id));
    }
    @GetMapping("{id}")
    public R getById(@PathVariable Integer id) {
        System.out.println("参数----》"+id);
        if(personalDiariesService.getById(id)==null){
            return  R.fail("id不存在");
        }

        return  R.success(personalDiariesService.getById(id));
    }


    @GetMapping("{currentPage}/{pageSize}")
    public R getAllPage(@PathVariable int currentPage, @PathVariable int pageSize, PersonalDiaries personalDiaries){
        System.out.println("参数----》"+personalDiaries);
        IPage<PersonalDiaries> pagesendBack=personalDiariesService.getPage(currentPage,pageSize,personalDiaries);
        return R.success(pagesendBack);
    }

    //分页条件查询
    @GetMapping("/list")
    public R<Map<String,Object>> getpersonalDiariesList(@RequestParam(value="createDate",required=false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date  createDate,
                                                        @RequestParam (value="title",required=false) String  title,
                                                        @RequestParam (value="tags",required=false) String  tags,
                                                        @RequestParam (value="mood",required=false) String  mood,
                                                        @RequestParam (value="pageNo",required=false) Long  pageNo,
                                                        @RequestParam (value="pageSize",required=false) Long  pageSize,
                                                        @RequestParam(value="sortField", required = false, defaultValue = "id") String sortField,
                                                        @RequestParam(value="sortOrder", required = false, defaultValue = "desc") String sortOrder // 新增排序字段和排序顺序
    ){
        LambdaQueryWrapper<PersonalDiaries> lqw = new LambdaQueryWrapper<>();
        if (createDate != null) {
            String createDateString = new SimpleDateFormat("yyyy-MM-dd").format(createDate);
            lqw.eq(StringUtils.hasLength(createDateString), PersonalDiaries::getCreateDate, createDateString);
        }
        lqw.eq(StringUtils.hasLength(title),PersonalDiaries::getTitle,title);
        lqw.eq(StringUtils.hasLength(tags),PersonalDiaries::getTags,tags);
        lqw.eq(StringUtils.hasLength(mood),PersonalDiaries::getMood,mood);
        // 根据sortField和sortOrder进行排序
        if (StringUtils.hasLength(sortField)) {
            boolean isDesc = "desc".equalsIgnoreCase(sortOrder);
            if (isDesc) {
                lqw.orderByDesc(PersonalDiaries::getId);
            } else {
                lqw.orderByAsc(PersonalDiaries::getId);
            }
        }
        Page<PersonalDiaries> page = new Page<>(pageNo,pageSize);
        personalDiariesMapper.selectPage(page,lqw);
        Map<String,Object> data = new HashMap<>();
        data.put("total",page.getTotal());
        data.put("rows",page.getRecords());
        return R.success(data);

    }


}
